# -*- coding: utf-8 -*-
import time
import logging
import os
import mechanize
import re
import sys

def ensureFolderExist(path):
    folderPath = os.path.dirname(path)
    if not os.path.exists(folderPath):
        os.makedirs(folderPath, 0777)

def getLogger(name, fm='', path=''):
    if fm == '': fm = "%(asctime)-15s %(levelname)-5s %(message)-20s"
    logging.basicConfig(format=fm)
    logger = logging.getLogger(name)
    if path != '':
        ensureFolderExist(path)
        handler = logging.FileHandler(path)
        handler.setFormatter(logging.Formatter(fm))
        logger.addHandler(handler)
    logger.setLevel(logging.DEBUG)
    return logger

def request():
    url = "http://mana.vn/testkey.php?REQUESTID={0}&USERID=mana&PASSWORD=mana2011&ACTIVEID=12345&IMEI=0123456789&PRODUCTID=00&LICENSETYPEID=12&PHONENO=0123456789".format(time.time())
    try:
        res = mechanize.urlopen(url)
        responseUrl = res.geturl()
        responseData = res.read()
        if responseData != '':
            m = re.search(r'<errorID>(\d)</errorID>', responseData)
            errorId = m.group(1)
            logger.debug("{0} {1}".format(errorId, responseUrl))
        else:
            logger.error("-1 {0} {1}".format(url, "Không lấy được nội dung từ url này"))
    except:
        logger.error("-1 {0} {1}".format(url, str(sys.exc_info())))

if __name__ == '__main__':
    logger = getLogger('TestKey', '', '/tmp/test_key_request.log')
    print('start request testkey')
    request()
    print('finished request testkey')
    os._exit(1)
